package zkclient;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.IZkStateListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;

import java.util.List;

public class Sample {

    public static void main(String[] args) {
        //连接Zookeeper
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        //创建节点
        zkClient.create("/root", "server data", CreateMode.PERSISTENT);
        //创建子节点
        zkClient.create("/root/server", "server data", CreateMode.EPHEMERAL);
        //获取子节点
        List<String> children = zkClient.getChildren("/root");
        //编辑子节点
        for (String item : children) {
            System.out.println(item);
        }
        //获取子节点的数量
        Integer number = zkClient.countChildren("/root");
        //判断节点是否存在
        if (zkClient.exists("/root")) {
            System.out.println("存在");
        }
        ;
        //写入数据
        zkClient.writeData("/root/child", "哈哈哈");
        //读取节点数据
        Object object = zkClient.readData("/root/child");
        //删除节点
        zkClient.delete("/root/child");


        //Listener
        zkClient.subscribeChildChanges("/root", new IZkChildListener() {
            @Override
            public void handleChildChange(String arg0, List<String> arg1) throws Exception {
                System.out.println("子节点的变化");
            }
        });
        zkClient.subscribeDataChanges("/root", new IZkDataListener() {
            @Override
            public void handleDataDeleted(String arg0) {
                System.out.println("数据被删除");
            }
            @Override
            public void handleDataChange(String arg0, Object arg1) {
                System.out.println("数据被更改");
            }
        });
        zkClient.subscribeStateChanges(new IZkStateListener() {
            @Override
            public void handleStateChanged(Watcher.Event.KeeperState arg0) {
                System.out.println("数据状态改变");
            }
            @Override
            public void handleNewSession() {
                System.out.println("当session expire异常重新连接时，由于原来的所有的watcher和EPHEMERAL节点都已失效，可以在这里进行相应的容错处理");
            }
            @Override
            public void handleSessionEstablishmentError(Throwable throwable) {

            }
        });
    }
}
